package com.example.tourmemory.data.record;

import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.util.ArrayList;

public class MarkerManager {
    private final ArrayList<Marker> markerList = new ArrayList<>();
    private TencentMap tencentMap;

    private static class onMarkerClickListener implements TencentMap.OnMarkerClickListener{
        @Override
        public boolean onMarkerClick(Marker marker) {
            // 点击标记时，显示信息窗口
            if(marker.isInfoWindowShown()) {
                marker.hideInfoWindow();
                return false;
            }
            marker.showInfoWindow();
            return false;
        }
    }

    public void Initialize(RecordManager recordManager, TencentMap tencentMap) {
        this.tencentMap = tencentMap;
        tencentMap.setOnMarkerClickListener(new onMarkerClickListener());
        Update(recordManager);
    }

    public void Update(RecordManager recordManager) {
        // 更新数据
        if(tencentMap == null)
            return;
        clear();
        for(int i = 0; i < recordManager.size(); i++)
            add(recordManager.get(i));
    }

    public void clear() {
        // 清除数据
        for(Marker marker: markerList) {
            marker.remove();
        }
        markerList.clear();
    }

    public void add(RecordData record) {
        // 创建新标记
        if(tencentMap == null)
            return;
        // 标记显示地址、描述，点击时可以显示或隐藏信息窗口
        MarkerOptions markerOptions = new MarkerOptions(record.getLatLng());
        markerOptions.title(record.getPositionName())
                .snippet(record.getDescription());
        Marker marker = tencentMap.addMarker(markerOptions);
        marker.setClickable(true);
        markerList.add(tencentMap.addMarker(markerOptions));
    }

    public void remove(int index) {
        // 移除指定数据
        if(markerList.size() <= index)
            return;
        markerList.get(index).remove();
        markerList.remove(index);
    }

    public Marker get(int index) {
        return markerList.get(index);
    }

    public int size() {
        return markerList.size();
    }

    public boolean isEmpty() {
        return markerList.isEmpty();
    }
}
